<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <el-tree
          :data="schooltree"
          @node-click="handleNodeClick"
          :highlight-current="true"
          :default-expand-all="true"
          :expand-on-click-node="false"
          empty-text="数据正在加载中..."
        ></el-tree>
      </el-col>

      <el-col :span="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="showSearch">
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
              <campus @schoolCampus="searchhandleSchoolCampus" :selectValue="queryParams.schoolCampusId"></campus>

              <el-form-item label="采购日期" prop="purchaseDate">
                <el-date-picker clearable v-model="queryParams.purchaseDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择采购日期" />
              </el-form-item>

              <el-form-item label="校验员" prop="checkOperator">
                <el-input v-model="queryParams.checkOperator" placeholder="请输入校验员" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['canteen:food:add']">新增 </el-button>
          </el-col> -->

              <el-col :span="1.5">
                <el-button type="primary" plain icon="upload" @click="handledBatchUpload" v-hasPermi="['canteen:food:add']">批量导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['canteen:food:edit']"
                  >修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['canteen:food:remove']"
                  >删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['canteen:food:export']">导出 </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
          </template>

          <el-table
            v-loading="loading"
            :data="foodList"
            @selection-change="handleSelectionChange"
            @header-click="handleCellMouseEnter"
            v-bind:border="showborder"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="校区" align="center" prop="schoolCampusName" v-if="columns[6].visible" />
            <el-table-column label="食材名称" align="center" prop="foodName" />
            <el-table-column label="采购日期" align="center" prop="purchaseDate" width="180" v-if="columns[0].visible">
              <template #default="scope">
                <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预采购" align="center" prop="prePurchaseQuantity" v-if="columns[2].visible" />
            <el-table-column label="单位" align="center" prop="unit" v-if="columns[1].visible" />
            <el-table-column label="采购净重" align="center" prop="purchaseNetWeight" v-if="columns[3].visible" />
            <el-table-column label="采购毛重" align="center" prop="purchaseGrossWeight" v-if="columns[4].visible" />
            <el-table-column label="校验员" align="center" prop="checkOperator" v-if="columns[5].visible" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="校验食材" placement="top">
                  <el-button link type="primary" icon="check" @click="handleUpdate(scope.row)" v-hasPermi="['canteen:food:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['canteen:food:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改食材管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="foodFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
        <campus @schoolCampus="handleSchoolCampus" @schoolCampuslength="handlegetSchoolCampus" :selectValue="form.schoolCampusId"></campus>
        <el-row>
          <el-col :span="12">
            <el-form-item label="食材名称" prop="foodName">
              <el-input v-model="form.foodName" placeholder="请输入食材名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker clearable v-model="form.purchaseDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预采购" prop="prePurchaseQuantity">
              <el-input v-model="form.prePurchaseQuantity" placeholder="请输入预采购" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购净重" prop="purchaseNetWeight">
              <el-input v-model="form.purchaseNetWeight" placeholder="请输入采购净重" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购毛重" prop="purchaseGrossWeight">
              <el-input v-model="form.purchaseGrossWeight" placeholder="请输入采购毛重" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="校验员" prop="checkOperator">
              <el-input v-model="form.checkOperator" placeholder="请输入校验员" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <ExcelUpload
      @upload-success="handleUpladeResult"
      @upload-cancel="handleCancel"
      :title="title"
      :objectName="objectName"
      :templatePath="templatePath"
      :contentType="contentType"
      v-model="batchImport"
      :uploadPath="uploadPath"
      :size="10"
    ></ExcelUpload>
  </div>
</template>

<script setup name="Food" lang="ts">
    import {
        listFood,
        getFood,
        delFood,
        addFood,
        updateFood
    } from '@/api/canteen/food';
    import {
            FoodVO,
            FoodQuery,
            FoodForm
    } from '@/api/canteen/food/types';

    import { getSchoolTreeNode } from "@/api/school/campus";

    import campus from '@/components/campus/index.vue';
    import ExcelUpload from '@/components/ExcelUpload/index.vue';

    const {proxy} = getCurrentInstance() as ComponentInternalInstance;

    const foodList = ref<FoodVO[]>([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref<Array<string | number>>([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const formLabelWidth = '120px';
    const showborder = ref(false)

    const queryFormRef = ref<ElFormInstance>();
    const foodFormRef = ref<ElFormInstance>();


    const schoolCampuslength = ref<number | null>(null); // 定义用于保存校区数量或其他数值

    //左侧树
    const schooltree = ref<FoodVO[]>([])

    const checkOperator = ref();


const title = ref("");

//excel导入相关
const batchImport = ref(false);
// const bucketName = ref("templates")
const objectName = ref("食材导入模板.xls")
const templatePath = ref("canteen/food/importTemplate");
const contentType = ref("application/octet-stream")
const uploadPath = ref("canteen/food/upload");


    const dialog = reactive<DialogOption>({
        visible: false,
        title: ''
    });

    const initFormData: FoodForm = {
                        foodId: undefined,
                        foodName: undefined,
                        purchaseDate: undefined,
                        purchaseQuantity: undefined,
                        unit: undefined,
                        prePurchaseQuantity: undefined,
                        purchaseNetWeight: undefined,
                        purchaseGrossWeight: undefined,
                        checkOperator: undefined,
                        schoolCampusId: undefined,
                        remark: undefined
    }
    const data = reactive<PageData<FoodForm, FoodQuery>>({
        form: {...initFormData},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
                            foodName: undefined,
                            purchaseDate: undefined,
                            purchaseQuantity: undefined,
                            unit: undefined,
                            prePurchaseQuantity: undefined,
                            purchaseNetWeight: undefined,
                            purchaseGrossWeight: undefined,
                            checkOperator: undefined,
                            schoolCampusId: undefined,
            params: {
            }
        },
        rules: {
                            foodName: [
                            {
                                required: true, message: "食材名称不能为空", trigger: "blur" }
                        ],
                            purchaseDate: [
                            {
                                required: true, message: "采购日期不能为空", trigger: "blur" }
                        ],

                            unit: [
                            {
                                required: true, message: "单位不能为空", trigger: "blur" }
                        ],
                            prePurchaseQuantity: [
                            {
                                required: true, message: "预采购不能为空", trigger: "blur" }
                        ],
                            schoolCampusId: [
                            {
                                required: true, message: "校区id不能为空", trigger: "blur" }
                        ],
        }
    });

    const {queryParams, form, rules} = toRefs(data);

    /** 查询食材管理列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listFood(queryParams.value);
            foodList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }

    /** 表单重置 */
    const reset = () => {
        form.value = {...initFormData};
            foodFormRef.value?.resetFields();
    }

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value?.resetFields();
        handleQuery();
    }

    /** 多选框选中数据 */
    const handleSelectionChange = (selection: FoodVO[]) => {
        ids.value = selection.map(item => item.foodId);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        dialog.visible = true;
        dialog.title = "添加食材管理";
    }

    /** 修改按钮操作 */
    const handleUpdate = async (row?: FoodVO) => {
        reset();
        const _foodId = row?.foodId || ids.value[0]
        const res = await getFood(_foodId);
        if(checkOperator.value!=null&&form.value.checkOperator ==null){
          res.data.checkOperator =checkOperator.value
        }
        Object.assign(form.value, res.data);
        dialog.visible = true;
        dialog.title = "食材校验";
    }






    /** 提交按钮 */
    const submitForm = () => {
            foodFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.foodId) {
                    await updateFood(form.value).finally(() =>  buttonLoading.value = false);
                } else {
                    await addFood(form.value).finally(() =>  buttonLoading.value = false);
                }
            checkOperator.value = form.value.checkOperator;
                proxy?.$modal.msgSuccess("修改成功");
                dialog.visible = false;
                await getList();
            }
        });
    }

    /** 删除按钮操作 */
    const handleDelete = async (row?: FoodVO) => {
        const _foodIds = row?.foodId || ids.value;
        await proxy?.$modal.confirm('是否确认删除食材管理编号为"' + _foodIds + '"的数据项？').finally(() => loading.value = false);
        await delFood(_foodIds);
        proxy?.$modal.msgSuccess("删除成功");
        await getList();
    }

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy?.download('canteen/food/export', {
            ...queryParams.value
        }, `food_${new Date().getTime()}.xlsx`)
    }

    onMounted(() => {
        getList();
    });


    /** 列信息 */
    const columns = ref([
                {key: 0, label: `采购日期`, visible: true},
                {key: 1, label: `单位`, visible: true},
                {key: 2, label: `预采购`, visible: true},
                {key: 3, label: `采购净重`, visible: true},
                {key: 4, label: `采购毛重`, visible: true},
                {key: 5, label: `校验员`, visible: true},
                {key: 6, label: `校区id`, visible: true},
    ]);


    function handleCellMouseEnter() {
        showborder.value = !showborder.value;
    }


function handleUpladeResult(value: any) {
    if (value) {
        batchImport.value = false;
        getList();
    }
}
function handleCancel(value: boolean) {
    batchImport.value = value;
}

function handledBatchUpload() {
    title.value = "批量导入食材";
    batchImport.value = true;
}
function searchhandleSchoolCampus(value: number|undefined) {
 data.queryParams.schoolCampusId = value;
}

function handleSchoolCampus(value: string | number) {
  console.log("handleSchoolCampus",value);

  // 修复：使用 ?? 将 null/undefined 转换为 undefined
  data.form.schoolCampusId = value ;

}

function handlegetSchoolCampus(value: number|null) {
  schoolCampuslength.value = value;
}


function handleNodeClick(data:any) {
    if (data.schoolId == null) {
        console.log("handleNodeClick",data)
        queryParams.value = data;
        getList();
    }
}

function schoolTreeNode() {
    loading.value = true;
    getSchoolTreeNode().then(response => {
      console.log(response);
        schooltree.value = response.data;
        loading.value = false;
    });


}

//初始化加载学校树
schoolTreeNode();
</script>
